//
//  YXNetWorkModel.swift
//  SinaWeiBo
//
//  Created by Vergil on 2017/6/13.
//  Copyright © 2017年 Vergil. All rights reserved.
//

import UIKit

private let contentFilePath = "userAccount.json"

class YXNetWorkModel: NSObject {
    
    /// 登录状态识别码
    var access_token: String? //= "2.00lCr7pGnigHzB405ec4dccagjRw5C"
    /// access_token的生命周期，单位是秒数.
    var expires_in: TimeInterval = 0 {
        didSet {
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 用户代号
    var uid: String?
    /// 过期日期
    var expires_date: Date?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        //路径
        let dirDic = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (dirDic as NSString).appendingPathComponent(contentFilePath)
        
        guard let data = NSData(contentsOfFile: jsonPath),
        let dic = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : Any]  else {
            return
        }
        
        yy_modelSet(with: dic!)
        
        //账户过期操作
        if expires_date?.compare(Date()) != .orderedDescending {
            //过期
            access_token = nil
            uid = nil
            
            try? FileManager.default.removeItem(atPath: jsonPath)
            
        }
        
    }
    
    //保存账号
    func saveUserAccount() {
        
        //模型转字典
        var dic = (self.yy_modelToJSONObject() as? [String : Any]) ?? [:]
        //删除expires_in
        dic.removeValue(forKey: "expires_in")
        //路径
        let dirDic = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (dirDic as NSString).appendingPathComponent(contentFilePath)
        //dic序列化data
        guard let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
             else {
                return
        }
        print(jsonPath)
        //写入
        (data as NSData).write(toFile: jsonPath, atomically: true)
    }
    
}
